package com.atguigu.gmall.index.config;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.feign.GmallPmsClient;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**布隆过滤器 用于缓存穿透  保存的是一级分类的id
 * @author Jia Fa
 * @create 2021-12-13 19:53
 */
@Configuration
public class BloomFilterConfig {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private GmallPmsClient pmsClient;

    private static final String KEY_PREFIX="index:cates:";

    @Bean
    public RBloomFilter<String> bloomFilter(){
        // 初始化
        RBloomFilter<String> bloomFilter = this.redissonClient.getBloomFilter("index:bloom:filter");
        bloomFilter.tryInit(30, 0.01);
        // 远程查询一级分类下的所有信息
        ResponseVo<List<CategoryEntity>> listResponseVo = this.pmsClient.categoryByPid(0l);
        List<CategoryEntity> categoryEntities = listResponseVo.getData();
        // 设置到bloom  一级分类的id就是布隆过滤器的key值  遍历获得所有id

        categoryEntities.forEach(categoryEntity -> {
            bloomFilter.add(KEY_PREFIX+"["+categoryEntity.getId()+"]");  //index:cates:[pid]
        });
        return bloomFilter;


    }
}
